package com.tn.service.truck;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gitee.hifong45.FE;
import com.gitee.hifong45.Kv;
import com.gitee.hifong45.Msg;
import com.tn.controller.alarm.common.constants.Constants;
import com.tn.controller.alarm.common.enums.TruckStatusEnum;
import com.tn.controller.alarm.common.model.external.producer.vo.WhiteListMemberVO;
import com.tn.controller.alarm.common.model.truck.BindTruckDto;
import com.tn.controller.alarm.common.model.truck.TruckDO;
import com.tn.dao.mbpdao.*;
import com.tn.dao.weigh.IWeighDao;
import com.tn.vo.TruckInfoMinVo;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TruckService {
    @Resource
    TruckinfoMapper truckinfoMapper;
    @Resource
    TruckinfoMinVoMapper truckinfoMinVoMapper;
    @Resource
    WhitelistMapper whitelistMapper;

    @Autowired
    IWeighDao truckinfoDao;


    @Autowired
    private IWeighDao weighDao;

    public TruckDO getTruckInfoByCardId(String tagId) {

        List<Truckinfo> ti = truckinfoMapper.selectList(new QueryWrapper<Truckinfo>()
                .eq("tagid", tagId)
                .eq("binding_status", Constants.BINDING_STATUS_ON) // 绑定的
                .orderByDesc("id")
        );
        if(ti.size() == 0) {
            return null;
        }
        TruckDO td = BeanUtil.copyProperties(ti.get(0), TruckDO.class);
        return td;
    }

    public List<TruckInfoMinVo> getTruckAndTag() {
        var lst = truckinfoMinVoMapper.selectList(new QueryWrapper<TruckInfoMinVo>()
                .select("id", "license", "tagid", "null as diff")
                .gt("in_time", DateUtil.beginOfDay(DateUtil.date()))
                .lt("in_time", DateUtil.endOfDay(DateUtil.date()))
                .eq("binding_status", Constants.BINDING_STATUS_ON) // 绑定的
                .ne("state", Constants.STATUS_UNKNOWN)
                .ne("state", TruckStatusEnum.ALREADY_OUT.getStatus())
                .orderByDesc("id")
        );
        return lst;
    }

    public boolean setTruckAndCardId(String cardId, String license) {
        List<Truckinfo> lst = truckinfoMapper.selectList(new QueryWrapper<Truckinfo>()
                        .eq("license", license)
                        .ne("state", Constants.STATUS_FINISHED)
                        .orderByDesc("id"));
        FE.trueThrow(lst.size()==0, Msg.NOT_FOUND, "车牌无数据: " + license);
        Truckinfo ti = lst.get(0);
        ti.setTagid(cardId);
        ti.setBindingStatus(Constants.BINDING_STATUS_ON);
        truckinfoMapper.updateById(ti);

        return true;
    }

    public Kv checkTruckInWhiteList(String license) {
        var lst = whitelistMapper.selectList(new QueryWrapper<Whitelist>()
                .eq("license", license)
                .ne("state", Constants.STATUS_UNKNOWN)
                .ne("state", Constants.STATUS_FINISHED)
                .ne("state", TruckStatusEnum.ALREADY_OUT.getStatus())
                .orderByDesc("id")
        );
        Whitelist wl = lst.size() > 0 ? lst.get(0) : new Whitelist();
        //查询距离当前时间最近的取皮重量
        Map<String,Object>map= truckinfoDao.selectQMLastWeigh(license);
        Double weight=null;
        if(!MapUtils.isEmpty(map)){
           if (map.get("state")!=null && "0".equals(map.get("state").toString())){
               weight=Double.valueOf(map.get("weight").toString());
           }
        }
        //查询车关联的任务号对应的物流公司
       String consignCompanyName= truckinfoDao.selectCompany(wl.getTaskNo(),wl.getGoodsName());
        return Kv.of("result", lst.size() > 0 ? "Y" : "Nde",
                "license", license,
                "taskNo", wl.getTaskNo(),
                "goodsName", wl.getGoodsName(),
                "company", wl.getCompany(),
                "dirver", wl.getDriver(),
                "shipNo", wl.getShipNo(),
                "tareWeight",weight,
                "consignCompanyName",consignCompanyName
        );
    }

    public Integer getInGateTruck() {
        var lst = truckinfoMinVoMapper.selectList(new QueryWrapper<TruckInfoMinVo>()
                .select("id", "license", "in_time", "cast((DATEDIFF( second, in_time, GETDATE())) as decimal(18,0)) as diff")
                .isNotNull("in_time")
                .gt("in_time", LocalDateTimeUtil.offset(LocalDateTime.now(), -1, ChronoUnit.DAYS))
                .ge("state", TruckStatusEnum.ALREADY_OUT.getStatus())
                .orderByDesc("id")
        );
        return lst.size();
    }
    public List<TruckInfoMinVo> getWorkingTruck() {
        var lst = truckinfoMinVoMapper.selectList(new QueryWrapper<TruckInfoMinVo>()
                .select("id", "license", "in_time", "cast((DATEDIFF( second, in_time, GETDATE())) as decimal(18,0)) as diff")
                .isNotNull("in_time")
                .gt("in_time", LocalDateTimeUtil.offset(LocalDateTime.now(), -1, ChronoUnit.DAYS))
                .ge("state", TruckStatusEnum.ALREADY_IN.getStatus())
                .le("state", TruckStatusEnum.ALREADY_OUT.getStatus())
                .orderByDesc("id")
        );

        return lst;
    }


    public Kv setTruckOutGate(String license, String taskNo, Integer status) {
        var ti = new Truckinfo();
        ti.setLicense(license);
        ti.setTaskNo(taskNo);
        ti.setState(status);
//        ti.setState(TruckStatusEnum.ALREADY_OUT.getStatus());
        int n = truckinfoMapper.update(ti, new QueryWrapper<Truckinfo>()
                .eq("license", license)
                .eq("task_no", taskNo)
        );
        log.info("更新车出闸：{} - {}，共 {} 条", license, taskNo, n);
        return Kv.of("license", license, "taskNo", taskNo, "num", n);
    }

    public List<BindTruckDto> getBindInfoLicense() {
        //查询当前车牌绑定采集卡集合
        List<BindTruckDto> bindInfoLicenseList = truckinfoDao.getBindInfoLicense();
        if(CollectionUtils.isEmpty(bindInfoLicenseList)){
            return new ArrayList<BindTruckDto>();
        }
        for (BindTruckDto bindTruckDto : bindInfoLicenseList) {
            //根据车牌查询最新一条过磅记录
            Weightloginfo weightloginfo=weighDao.selectLastWeigh(bindTruckDto);
            if(weightloginfo!=null){
                bindTruckDto.setCompany(weightloginfo.getCustomerCompanyName());
                bindTruckDto.setConsignName(weightloginfo.getConsignCompanyName());
                bindTruckDto.setWeightId(weightloginfo.getWeightid());
                bindTruckDto.setTakeCarTime(weightloginfo.getCreateTime());
            }

        }
        return bindInfoLicenseList;
    }

//    public Map getBillPoundMap(String license) {
//        Map map = truckinfoDao.getBillPoundMap(license);
//        String shipNo = (String) map.get("shipNo");
//        String workProcessName = (String) map.get("workProcessName");
//        String taskNo = (String) map.get("taskNo");
//        String positions = (String) map.get("positions");
//        if(StringUtils.isNotBlank(positions)){
//            try {
//                List<WhiteListMemberVO.Position> positionList = JSONArray.parseArray(positions, WhiteListMemberVO.Position.class);
//                positionList = positionList.subList(0,1);
//                positionList.forEach(e -> {
//                    map.put("warehouseName",e.getWarehouseName());
//                    map.put("cargoSpaceName",e.getCargoSpaceName());
//                    map.put("statckName",e.getStatckName());
//                    String position = e.getWarehouseName() +"-" + e.getCargoSpaceName()+"-" + e.getStatckName();
//                    map.put("position",position);
//                    map.remove("positions");
//                });
//            }catch (Exception e){
//                log.error("白名单位置信息解析异常:{}",e.getMessage());
//            }
//
//        }
//        if(StringUtils.isNotBlank(shipNo) && StringUtils.isNotBlank(workProcessName) && StringUtils.isNotBlank(taskNo)){
//            String taskNumber = shipNo + "(" + workProcessName + ")-" + taskNo;
//            map.put("taskNumber",taskNumber);
//        }
//        return map;
//    }
    public Map getBillPoundMap(String license) {
        Map map = truckinfoDao.getBillPoundMap(license);
        String shipNo = (String) map.get("shipNo");
        String noticeSystem = (String) map.get("noticeSystem");
        String taskNo = (String) map.get("taskNo");
        String positions = (String) map.get("positions");
        if(StringUtils.isNotBlank(positions)){
            List<WhiteListMemberVO.Position> positionList = JSONArray.parseArray(positions, WhiteListMemberVO.Position.class);
            if(positionList!= null && positionList.size() > 0){
                positionList = positionList.subList(0,1);
                positionList.forEach(e -> {
                    map.put("warehouseName",e.getWarehouseName());
                    map.put("cargoSpaceName",e.getCargoSpaceName());
                    map.put("statckNoName",e.getStatckName());
                    String position = e.getWarehouseName() +"-" + e.getCargoSpaceName()+"-" + e.getStatckName();
                    map.put("position",position);
                    map.remove("positions");
                });
            }
        }
        if(StringUtils.isNotBlank(shipNo) && StringUtils.isNotBlank(noticeSystem) && StringUtils.isNotBlank(taskNo)){
            String taskNumber = shipNo + "(" + noticeSystem + ")-" + taskNo;
            map.put("taskNumber",taskNumber);
        }
        return map;
    }
}

